<!-- src/components/LineChart.vue -->
<template>
  <div class="chart-wrapper">
    <canvas ref="lineCanvas"></canvas>
  </div>
</template>

<script>
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);

export default {
  name: 'LineChart',
  props: {
    chartData: {
      type: Array,
      default: () => []
    },
    sensorLabel: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chartInstance: null
    };
  },
  watch: {
    chartData: {
      deep: true,
      immediate: true,
      handler() {
        this.drawOrUpdateChart();
      }
    }
  },
  methods: {
    drawOrUpdateChart() {
      if (!this.chartInstance) {
        const ctx = this.$refs.lineCanvas.getContext('2d');
        this.chartInstance = new Chart(ctx, {
          type: 'line',
          data: { labels: [], datasets: [] },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              y: {}
            }
          }
        });
      }
      const labels = this.chartData.map(item =>
          new Date(item.createdTime).toLocaleTimeString()
      );
      const values = this.chartData.map(item => item.value);

      let minVal = Math.min(...values);
      let maxVal = Math.max(...values);
      if (minVal === maxVal) {
        minVal -= 1;
        maxVal += 1;
      }

      this.chartInstance.data = {
        labels,
        datasets: [
          {
            label: this.sensorLabel || '传感器值',
            data: values,
            borderColor: 'rgba(75, 192, 192, 1)',
            backgroundColor: 'rgba(75, 192, 192, 0.2)',
            borderWidth: 2,
            fill: true,
            tension: 0.1
          }
        ]
      };

      this.chartInstance.options.scales.y.min = minVal;
      this.chartInstance.options.scales.y.max = maxVal;
      this.chartInstance.update();
    }
  }
};
</script>

<style scoped>
.chart-wrapper {
  width: 100%;
  height: 250px;
  position: relative;
}

canvas {
  width: 100%;
  height: 100%;
}
</style>
